package DataCrawler;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import org.apache.commons.io.FileUtils;

public class DataProcessor {
    private JSONObject json;
    public String resDir = "src\\main\\resources\\";
    public DataProcessor() {
        json = null;
    }

    public void parseString(String s) {
        json = JSONObject.parseObject(s);
    }
    
    public void parseStringFromFile(String filename) {
        String s = null;
        try{
            s = FileUtils.readFileToString(new File(resDir+filename), Charset.forName("utf8"));
        }
        catch (IOException e) {
            System.err.println("[DP] 文件不能打开。");
        }
        json = JSONObject.parseObject(s);
    }

    public List<String> getCidList() {
        ArrayList<String> ans = new ArrayList<String>();
        var sections = json.getJSONArray("sections");
        JSONArray all = sections.getJSONObject(0).getJSONArray("episodes");
        all.addAll(sections.getJSONObject(1).getJSONArray("episodes"));

        for (int i = 0; i < all.size(); ++i) {
            ans.add(all.getJSONObject(i).getString("cid"));
        }
        return ans;
    }
    
    public static void main(String[] args) {
        DataProcessor dp = new DataProcessor();
        try{
            String text = FileUtils.readFileToString(new File(dp.resDir+"Page.json"), Charset.forName("utf8"));
            dp.parseString(text);
            var ls = dp.getCidList();
            for (String s : ls) {
                System.out.println(s);
            }

        }
        catch (IOException e) {
            System.err.println(e.getMessage());
        }
    }
}
